#pragma once

#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <string>
#include <queue>

const static int gcap = 5;

template <typename T>
class BlockQueue
{
public:
    BlockQueue(const int cap = gcap) : _cap(cap)
    {
        _productor_wait_num = 0;
        _consumer_wait_num = 0;
        pthread_mutex_init(&_lock, nullptr);
        pthread_cond_init(&_c_cond, nullptr);
        pthread_cond_init(&_p_cond, nullptr);
    }
    ~BlockQueue()
    {
        pthread_mutex_destroy(&_lock);
        pthread_cond_destroy(&_c_cond);
        pthread_cond_destroy(&_p_cond);
    }
    bool IsFull()
    {
        return _bq.size() >= _cap;
    }
    bool IsEmpty()
    {
        return !_bq.size();
    }
    void Pop(T *out)
    {
        pthread_mutex_lock(&_lock);
        while (IsEmpty()) // 防止1. pthread_cond_wait调用失败 2.伪唤醒问题
        {
            _consumer_wait_num++;
            pthread_cond_wait(&_c_cond, &_lock);
            _consumer_wait_num--;
        }
        *out = _bq.front();
        _bq.pop();

        if (_productor_wait_num > 0)
            pthread_cond_signal(&_p_cond);
        pthread_mutex_unlock(&_lock);
    }

    void Enqueue(const T &in)
    {
        pthread_mutex_lock(&_lock);
        while (IsFull())
        {
            _productor_wait_num++;
            pthread_cond_wait(&_p_cond, &_lock); // 1.自动释放锁 2.自动重新申请锁
            _productor_wait_num--;
        }
        _bq.push(in);

        if (_consumer_wait_num > 0)
            pthread_cond_signal(&_c_cond);
        pthread_mutex_unlock(&_lock);
    }

private:
    // 临界资源
    std::queue<T> _bq;
    int _cap;
    pthread_mutex_t _lock;

    pthread_cond_t _p_cond;
    pthread_cond_t _c_cond;

    int _productor_wait_num;
    int _consumer_wait_num;
};